using System.Collections;
using System.Collections.Generic;
using UnityEngine;

//用来控制测试流程的脚本
public class MatchTestFlow : MonoBehaviour
{
  [SerializeField]
  private BallResourcesSet _ballResourcesSet;
  [SerializeField]
  private FieldView _fieldView;
  [SerializeField]
  private FieldEngine _fieldEngine;
  [SerializeField]
  private GridBallReloader _ballReloader;

  private BagModel m_bagModel;

  private FieldModel m_ballFieldModel;

  private void Start() {
    /*目前的流程：
     *生成一个背包Model，填充初始数据（暂定的）
     *生成一个棋盘Model，用背包数据进行填充（填充方式是暂定的）
     *将棋盘Model丢给FieldView进行渲染
     */
    m_bagModel = new BagModel();
    Test_SetDefaultPropBallBag();

    _ballReloader.SetBagModel(m_bagModel);

    m_ballFieldModel = new FieldModel();
    var param = new FieldModel.Param {
      size = new Vector2Int(GlobalDef.COLUM_COUNT, GlobalDef.ROW_COUNT)
    };
    m_ballFieldModel.Init(param);
    Test_SetFieldModelFromBag();

    _fieldEngine.InitIfNot();
    _fieldEngine.SetModel(m_ballFieldModel);
    _fieldEngine.RegisterHolder(FieldView.HOLDER_KEY, _fieldView.GetRenderHolder());

    _ballResourcesSet.dict.InitIfNot();
    _fieldView.SetResourcesDict(_ballResourcesSet.dict);

    _fieldEngine.TriggerEmptyResolve(_fieldView.GetRenderHolder());
  }

  private FieldModel m_fieldCache;
  private void Update() {
    if (Input.GetKeyDown(KeyCode.I))
    {
      print("trigger");
      _fieldEngine.TriggerEmptyResolve();
    }
  }

  public void Test_SetDefaultPropBallBag() { //测试代码，设置初始背包
    var itemTypeCount = GlobalDef.DEFAULT_TYPE_COUNT;//先定为7之后可以被遗物改变
    var itemNum = GlobalDef.DEFAULT_PROPBALL_COUNT;//每种道具球40个，之后可以被遗物改变

    for (int i = 0; i < itemTypeCount; i++)
    {
      m_bagModel.RegisterEntry(i);
      m_bagModel.UpdateEntry(i, itemNum, itemNum);
    }
  }

  public void Test_SetFieldModelFromBag() {//测试代码，从背包随机读取球填入棋盘
    foreach (var pos in m_ballFieldModel.gridModel.AllPosition())
    {
      var entry = m_bagModel.GetNotEmptyEntryRandomly();
      if (!entry.isValid)
      {
        return;
      }

      if (m_bagModel.TryConsume(entry.id, 1) == 0)
      {
        m_ballFieldModel.gridModel.CreateBallModelAt(BallInfo.Create(entry.id), pos);
      }
    }
  }
}
